#!/usr/bin/env python
# -*- encoding:utf-8 -*-

import sys
import os.path

import numpy as np
import cv2

from flask import Flask
from flask import request

import paddleocr.paddleocr

app = Flask(__name__)


paddleocr_path = paddleocr.__path__[0]


def get_default_args() -> dict:
    args = paddleocr.paddleocr.parse_args(mMain=True)
    return args.__dict__

def img_decode(content: bytes):
    np_arr = np.frombuffer(content, dtype=np.uint8)
    return cv2.imdecode(np_arr, cv2.IMREAD_COLOR)

@app.route('/api', methods=['POST'])
def ocr():
    os.chdir(paddleocr_path)
    picture_raw_data = request.get_data()
    img_data = img_decode(picture_raw_data)
    args = get_default_args()
    engine = paddleocr.PaddleOCR(**args)
    result = engine.ocr(img_data, det=True, rec=True, cls=False)
    return result


if __name__ == '__main__':
    from gevent.pywsgi import WSGIServer
    server = WSGIServer(('0.0.0.0', 5000), app)
    sys.argv = [sys.argv[0], '--use_gpu', 'false']
    server.serve_forever()
